package com.konsung.presenter.impl;

import android.text.TextUtils;
import com.google.gson.reflect.TypeToken;
import com.konsung.bean.AppPersonDto;
import com.konsung.bean.CheckData;
import com.konsung.bean.PatientBean;
import com.konsung.bean.PersonDownloadResponse;
import com.konsung.bean.QueryCommand;
import com.konsung.greendaoUtil.DBUtitl;
import com.konsung.greendaoUtil.GreenDaoManager;
import com.konsung.healthfile.R;
import com.konsung.kslibrary.base.BasePresenter;
import com.konsung.network.RequestUtils;
import com.konsung.network.URLManage;
import com.konsung.presenter.PatientDownloadPresenter;
import com.konsung.provide.ProviderReader;
import com.konsung.ui.PatientDownloadActivity;
import com.konsung.util.IdCardUtil;
import com.konsung.util.JsonUtils;
import com.konsung.util.StringUtil;
import com.konsung.util.ThreadManager;
import com.konsung.util.ToastUtils;
import com.konsung.util.UiUtils;
import com.konsung.util.constant.GlobalConstant;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.synjones.bluetooth.BmpUtil;


import org.apache.http.Header;
import org.apache.http.entity.StringEntity;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by xiangshicheng on 2018/12/11 0011.
 * 居民下载逻辑实现类
 */

public class PatientDownloadPresenterImpl extends BasePresenter<PatientDownloadActivity>
        implements PatientDownloadPresenter.Presenter {

    private int pageLimit = 5; //每页数量限制
    private int totalPersent = 0; //下载总数
    private int percentValue = 0; //进度条

    @Override
    public List<PatientBean> queryPatient(String condition, int page) {
        List<PatientBean> patientBeans = new ArrayList<>();
        UiUtils.showProgress(mvpView, UiUtils.getString(R.string.wait_for_load));
        final String url = URLManage.getInstance().downloadPatientList; //接口地址
        CheckData checkData = ProviderReader.getCheckData(mvpView);
        String orgId = "";
        if (checkData != null) {
            orgId = checkData.getCheckData().getOrgId(); //机构id
        }
        QueryCommand command = new QueryCommand();
        command.setOrgId(orgId);
        command.setPageStart((page - 1) * pageLimit);
        command.setPageRecords(pageLimit);
        if (!TextUtils.isEmpty(condition)) {
            command.setCondition(condition);
        }
        try {
            final StringEntity entity = new StringEntity(JsonUtils.toJsonString(command)
                    , "UTF-8");
            ThreadManager.getInstance().createShortPool().execute(new Runnable() {
                @Override
                public void run() {
                    RequestUtils.clientPost(mvpView, url, entity, callback);
                }
            });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return patientBeans;
    }

    @Override
    public void downloadSelectData(List<PatientBean> checkedPatients) {
        if (checkedPatients.size() == 0) {
            //没有选择数据
            ToastUtils.showShortToast(mvpView.getString(R.string.download_patient_empty));
            return;
        }
        UiUtils.showProgress(mvpView, mvpView.getString(R.string.wait_for_load));
        //比较服务器选择的数据和本地居民列表的数据，有重复的不进行下载
        List<PatientBean> localList = DBUtitl.queryAll(mvpView);
        List<PatientBean> diffList = getFiltrtDownData(checkedPatients, localList);
        if (diffList.size() > 0) {
            transformCardInsert(diffList);
        }
        UiUtils.hideProgress();
        ToastUtils.showShortToast(mvpView.getString(R.string.download_patient_ok));
        mvpView.resetView();
    }

    @Override
    public void queryAllPatient(String condition, final int page) {
        //下载全部数据
        final String url = URLManage.getInstance().downloadPatientList;
        CheckData checkData = ProviderReader.getCheckData(mvpView);
        String orgId = "";
        if (checkData != null) {
            orgId = checkData.getCheckData().getOrgId(); //机构id
        }
        QueryCommand command = new QueryCommand();
        command.setOrgId(orgId);
        command.setPageStart(page * 100);
        command.setPageRecords(100);
        if (!TextUtils.isEmpty(condition)) {
            command.setCondition(condition);
        }
        final AsyncHttpResponseHandler callback = new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                String json = new String(bytes);
                PersonDownloadResponse<AppPersonDto> datas = JsonUtils.toEntity(
                        json, new TypeToken<PersonDownloadResponse<AppPersonDto>>() {
                        }.getType());
                if (PatientDownloadActivity.isStopDownload) {
                    PatientDownloadActivity.isStopDownload = false;
                    UiUtils.post(new Runnable() {
                        @Override
                        public void run() {
                            mvpView.dismissDialog();
                        }
                    });
                    //停止全部下载
                    return;
                }
                if (!datas.resultCode.equals(GlobalConstant.SUCCESS)) {
                    return;
                }
                //请求成功
                final List<PatientBean> list = toPatients(datas.list);
                if (list.size() == 0) {
                    return;
                }
                //下载头像文件
                queryHeadPic(list);
                totalPersent += list.size();
                percentValue = totalPersent * 100 / Integer.valueOf(datas.entity);
                //比较服务器选择的数据和本地居民列表的数据，有重复的不进行下载
                List<PatientBean> localList = DBUtitl.queryAll(mvpView);
                //获取手动取消掉用户集合
                List<PatientBean> patientList = mvpView.getHandCancelList();
                if (patientList != null && patientList.size() > 0) {
                    localList.addAll(patientList);
                }
                List<PatientBean> diffList = getFiltrtDownData(list, localList);
                if (diffList.size() > 0) {
                    transformCardInsert(diffList);
                }
                UiUtils.post(new Runnable() {
                    @Override
                    public void run() {
                        mvpView.updateDialog(percentValue, totalPersent, page);
                    }
                });
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                UiUtils.post(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showShortToast(UiUtils.getString(R.string.request_timeout));
                        mvpView.dismissDialog();
                    }
                });
            }
        };

        try {
            final StringEntity entity = new StringEntity(JsonUtils.toJsonString(command)
                    , "UTF-8");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    RequestUtils.clientPost(mvpView, url, entity, callback);
                }
            }).start();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将card重新赋值
     *
     * @param diffList 所选数据
     */
    private void transformCardInsert(List<PatientBean> diffList) {
        GreenDaoManager.getPatientDao(mvpView).insertOrReplaceInTx(diffList);
    }

    /**
     * 获取比较后的下载的数据
     *
     * @param checkedPatients 选择服务器的数据
     * @param localList       本地已有的数据
     * @return 比较后的数据
     */
    private List<PatientBean> getFiltrtDownData(List<PatientBean> checkedPatients
            , List<PatientBean> localList) {
        if (localList.size() == 0) {
            //如果本地没有数据
            return checkedPatients;
        }
        for (PatientBean local : localList) {
            //遍历本地数据，服务器有，移除
            for (Iterator it = checkedPatients.iterator(); it.hasNext(); ) {
                PatientBean check = (PatientBean) it.next();
                if (!TextUtils.isEmpty(local.getIdcard())) {
                    if (local.getIdcard().equals(check.getIdcard())) {
                        //有相同的移除
                        it.remove();
                    }
                } else {
                    if (local.getName().equals(check.getName())) {
                        //有相同的移除
                        it.remove();
                    }
                }
            }
        }
        return checkedPatients;
    }

    /**
     * 网络接口回调
     */
    AsyncHttpResponseHandler callback = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String json = new String(responseBody);
            final PersonDownloadResponse<AppPersonDto> datas = JsonUtils.toEntity(json
                    , new TypeToken<PersonDownloadResponse<AppPersonDto>>() {
                    }.getType());
            if (!datas.resultCode.equals(GlobalConstant.SUCCESS)) {
                UiUtils.post(new Runnable() {
                    @Override
                    public void run() {
                        mvpView.showPatientList(null, "");
                        UiUtils.hideProgress();
                    }
                });
                return;
            }
            //结果请求成功
            final List<PatientBean> patientBeen = toPatients(datas.list);
            if (patientBeen.size() == 0) {
                UiUtils.post(new Runnable() {
                    @Override
                    public void run() {
                        mvpView.showPatientList(null, "");
                        UiUtils.hideProgress();
                    }
                });
                return;
            }
            //下载头像文件
            queryHeadPic(patientBeen);
            UiUtils.post(new Runnable() {
                @Override
                public void run() {
                    mvpView.showPatientList(patientBeen, datas.entity);
                    UiUtils.hideProgress();
                }
            });
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody
                , Throwable error) {
            UiUtils.post(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.showShortToast(mvpView.getString(R.string.request_timeout));
                    UiUtils.hideProgress();
                    mvpView.showPatientList(null, "");
                }
            });
        }
    };

    /**
     * 根据居民列表下载保存头像
     *
     * @param patientBeen patientBeen
     */
    private void queryHeadPic(List<PatientBean> patientBeen) {
        for (final PatientBean patientBean : patientBeen) {
            String bmpStr = patientBean.getBmpStr();
            if (TextUtils.isEmpty(bmpStr)) {
                continue;
            }
            downloadHeadPic(patientBean.getIdcard(), patientBean.getBmpStr());
        }
    }

    /**
     * 根据头像名下载保存头像
     *
     * @param headPicName headPicName
     * @param fileName    fileName
     */
    private void downloadHeadPic(final String fileName, String headPicName) {
        final String url = URLManage.getInstance().downloadPatientHead;
        final RequestParams params = new RequestParams();
        //固定参数 文件名和文件范围
        params.put("fileName", headPicName);
        params.put("rRange", "0-");
        final FileAsyncHttpResponseHandler callback = new FileAsyncHttpResponseHandler(mvpView) {
            @Override
            public void onFailure(int i, Header[] headers, Throwable throwable, File response) {
                throwable.printStackTrace();
            }

            @Override
            public void onSuccess(int i, Header[] headers, File response) {
                try {
                    File picFile = new File(BmpUtil.getHeadPicRootFile(), fileName + ".bmp");
                    if (picFile.exists() && picFile.length() == response.length()) {
                        UiUtils.post(new Runnable() {
                            @Override
                            public void run() {
                                mvpView.updateAdapter();
                            }
                        });
                        return;
                    } else {
                        if (!picFile.exists()) {
                            try {
                                if (!picFile.createNewFile()) {
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    //复制文件
                    BmpUtil.fileChannelCopy(response, picFile);
                    UiUtils.post(new Runnable() {
                        @Override
                        public void run() {
                            mvpView.updateAdapter();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    RequestUtils.clientPost(mvpView, url, params, callback);
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     *
     * 居民信息下载转换
     *
     * @param personDtos 转换前的数据
     * @return 转换后的居民信息列表
     */
    public static List<PatientBean> toPatients(List<AppPersonDto> personDtos) {
        ArrayList list = new ArrayList();
        if (personDtos == null || personDtos.size() <= 0) {
            return list;
        }

        for (AppPersonDto personDto : personDtos) {
            PatientBean patientBean = new PatientBean();
            patientBean.setName(StringUtil.getValidStr(personDto.getName()));
            patientBean.setIdcard(StringUtil.getValidStr(personDto.getCardNo()));
            patientBean.setAge(StringUtil.getValidInt(personDto.getAge()));
            patientBean.setSex(StringUtil.getValidIntInSex(personDto.getSex()));
            int bloodType = StringUtil.getValidInt(personDto.getBloodType());
            if (bloodType == 9) {
                bloodType = 0;
            }
            patientBean.setBlood(bloodType);
            patientBean.setContact(StringUtil.getValidStr(personDto.getTelePhone()));
            patientBean.setPatientType(StringUtil.getValidInt(personDto.getPatientType()));
            patientBean.setAddress(StringUtil.getValidStr(personDto.getAddress()));
            patientBean.setBmpStr(StringUtil.getValidStr(personDto.getHeadPortrait()));
            patientBean.setAddDate(System.currentTimeMillis());
            patientBean.setBirthday(IdCardUtil.getAgeForIdCard(patientBean.getIdcard()).getTime());
            list.add(patientBean);
        }
        return list;
    }
}
